using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace XmlObjects.XmlDocumentMarkup.XmlWriter
{
	public class AttributeWriter : IXmlSimpleEntity
	{
		public void Write(XmlNode node, object value, string name)
		{
			//  Assume that if the 
			XmlDocument parentDocument = node.OwnerDocument;
			if (parentDocument==null)
				parentDocument = (XmlDocument) node;

			XmlAttribute theAttribute = null;

			foreach (XmlAttribute anAttribute in node.Attributes)
			{
				if (anAttribute.Name.Equals(name))
				{
					theAttribute = anAttribute;
					break;
				}
			}

			if (theAttribute==null)
			{
				theAttribute = parentDocument.CreateAttribute(name);
				node.Attributes.Append(theAttribute);
			}
			if (value != null)
				theAttribute.Value = value.ToString();
		}

		public object Read(XmlNode node, string name)
		{
			foreach (XmlAttribute xmlAttribute in node.Attributes)
			{
				if (xmlAttribute.Name.Equals(name))
					return xmlAttribute.Value;
			}
			return null;
		}
	}
}
